package ar.uba.fi.tonyvaliente.commands;

import java.io.File;

import ar.uba.fi.tonyvaliente.documents.AddDocumentResult;
import ar.uba.fi.tonyvaliente.documents.DocumentManager;

public class AddDocumentCommand extends Command {

	private boolean recognized;
	private String path;

	public AddDocumentCommand(String[] args) {
		super(args);

		recognized = false;
		path = null;

		if (args.length > 0) {
			String command = args[0];
			command = command.toLowerCase();
			if (command.equals("-adddocument")) {
				recognized = true;
				if (args.length > 1) {
					path = args[1];
				}
			}
		}
	}

	private CommandResult addDocument() {
		AddDocumentResult addDocumentResult = DocumentManager.addDocument(path);
		if (addDocumentResult.isSuccess())
			return CommandResult.EXECUTE_SUCCESSFULLY;
		else
			return new CommandResult(true, false, addDocumentResult
					.getErrorMessage());
	}

	public CommandResult execute() {
		if (!recognized)
			return CommandResult.NOT_RECOGNIZED;

		if (path == null)
			return new CommandResult(true, false, "Missing document's path");

		if (!fileExists(path))
			return new CommandResult(true, false, "Document not exists");

		return addDocument();
	}

	public String getSignature() {
		return "-addDocument \"path to document\"";
	}

	public String getDescription() {
		return "Add specified document into the index";
	}

	public String[] getExamples() {
		return new String[] { String.format("-addDocument \"%s\"",
				"/etc/user/document.htm") };
	}

	private static boolean fileExists(String path) {
		File file = new File(path);
		return file.exists() && file.isFile();
	}
}
